var write = require('hy5b/backend/write')
var moment = require('moment')

var fs = write('mi4.enex');

var data = require('./data.json')
var arr = data[0]

fs.write('<?xml version="1.0" encoding="UTF-8"?>'
  + '<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export2.dtd">'
  + '<en-export export-date="20170816T181020Z" application="Evernote/Windows" version="6.x">');

for (var i = 0; i < arr.length; i++) {
  var box = arr[i]

  if (box.created_time) {
    handleContent('笔记', box)
  } else if (box.box_name) {
    var boxName = box.box_name;
    var boxContents = box.content;
    for (var j = 0; j < boxContents.length; j++) {
      var content = boxContents[j]
      handleContent(boxName, content);
    }
  }
}

fs.write('</en-export>\n')

function handleContent(title, content) {
  fs.write('<note>\n')
  var time = moment(content.created_time, 'YYYY年M月D日 HH:mm')
  var created = time.format('YYYYMMDDTHHmm') + '00Z'
  fs.write('<title>'+title +'</title>\n')
  fs.write('<content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>'
    + '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    + '<en-note><div>'
    + JSON.stringify(content.content)
        .replace(/\\n/, '')
        .replace(/\\n/g, '<br clear="none"/>')
        .replace(/^" */, '')
        .replace(/"$/, '')
    + '</div></en-note>]]></content>\n')
  fs.write('<created>'+created+'</created>\n')
  fs.write('</note>\n')
}